package demo.dangdang.elastic.job;

import java.util.LinkedList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

public class SimpleJobDemo implements SimpleJob {

    private static final Logger logger = LoggerFactory.getLogger(SimpleJobDemo.class);

    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info("schedule Job:{}", shardingContext);
        // 当前分片项
        int shardingItem = shardingContext.getShardingItem();
        // 分片总数
        int shardingTotalCount = shardingContext.getShardingTotalCount();
        logger.info("execute job: {},ShardingItem: {}", shardingContext.getJobName(), shardingItem);
        System.out.println(String.format("------Thread ID: %s, 任务总片数: %s, 当前分片项: %s", Thread.currentThread().getId(),
                shardingTotalCount, shardingItem));

        /**
         * 实际开发中，有了任务总片数和当前分片项，就可以对任务进行分片执行了。 <br>
         * 比如 SELECT * FROM user WHERE status = 0 AND MOD(id, shardingTotalCount) = shardingItem
         */
        String jobParameter = shardingContext.getJobParameter();

        LinkedList<Long> userIds = new LinkedList<>();
        if (userIds == null || userIds.isEmpty()) {
            logger.error("there is no user_id in collection:{}", "tableName");
            return;
        }

        while (!userIds.isEmpty()) {
            Long userId = userIds.poll();
            if (userId == null || userId % shardingTotalCount != shardingItem) {
                continue;
            }
            logger.info("执行JOB逻辑");
        }

    }
}
